#include "configutil.h"

#include <QDir>
#include <QStandardPaths>
#include <qapplication.h>
#include <response.h>

QString ConfigUtil::appConfigDir()
{
    QString path = configDir() + "android-repo-analyzer";
    mkdir(path);
    return path + QDir::separator();
}

QString ConfigUtil::appConfigFile(const QString &filename)
{
    return appConfigDir() + filename;;
}

QString ConfigUtil::getAppRepoConfig()
{
    return read(appConfigFile("repo.cfg"));
}

void ConfigUtil::setAppRepoConfig(QString &repoPath)
{
    write(appConfigFile("repo.cfg"), repoPath);
}

QVariantMap ConfigUtil::getAppSettingsConfig()
{
    QString content = read(appConfigFile("settings.json"));
    if (content.isEmpty()) {
        content = "{}";
        write(appConfigFile("settings.json"), content);
    }

    return Response(0, content).toMap();
}

void ConfigUtil::setAppSettingsConfig(const QVariantMap &config)
{
    write(appConfigFile("settings.json"), Response(0, config).toJson());
}

QString ConfigUtil::read(const QString &filepath)
{
    QFile file(filepath);
    file.open(QFile::ReadOnly);
    return file.readAll();
}

void ConfigUtil::write(const QString &filepath, const QString &content)
{
    QFile file(filepath);
    file.open(QFile::WriteOnly);
    file.write(content.toUtf8());
    file.flush();
}
